import i18n from '@/locales/config';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
// import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import { App, ConfigProvider, ConfigProviderProps, theme } from 'antd';
// import pt_BR from 'antd/lib/locale/pt_BR';
// import enUS from 'antd/locale/en_US';
// import vi_VN from 'antd/locale/vi_VN';
import zhCN from 'antd/locale/zh_CN';
// import zh_HK from 'antd/locale/zh_HK';
// import deDE from 'antd/locale/de_DE';
import dayjs from 'dayjs';
import advancedFormat from 'dayjs/plugin/advancedFormat';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import localeData from 'dayjs/plugin/localeData';
import weekOfYear from 'dayjs/plugin/weekOfYear';
import weekYear from 'dayjs/plugin/weekYear';
import weekday from 'dayjs/plugin/weekday';
import React, { ReactNode, useEffect, useState } from 'react';
import { ThemeProvider, useTheme } from './components/theme-provider';
import { TooltipProvider } from './components/ui/tooltip';
import storage from './utils/authorization-util';
// import { initSafeArea } from './utils/safe-area';

// 导入安全区域样式
import './styles/safe-area.css';
// import { initSafeArea } from './utils/safe-area';

dayjs.extend(customParseFormat);
dayjs.extend(advancedFormat);
dayjs.extend(weekday);
dayjs.extend(localeData);
dayjs.extend(weekOfYear);
dayjs.extend(weekYear);

const AntLanguageMap = {
  zh: zhCN,
};

const queryClient = new QueryClient();

type Locale = ConfigProviderProps['locale'];

function Root({ children }: React.PropsWithChildren) {
  const { theme: themeragflow } = useTheme();
  const getLocale = (lng: string) =>
    AntLanguageMap[lng as keyof typeof AntLanguageMap] ?? zhCN;

  const [locale, setLocal] = useState<Locale>(getLocale(storage.getLanguage()));

  i18n.on('languageChanged', function (lng: string) {
    storage.setLanguage(lng);
    setLocal(getLocale(lng));
  });

  return (
    <>
      <ConfigProvider
        theme={{
          token: {
            fontFamily: 'Inter',
          },
          algorithm:
            themeragflow === 'dark'
              ? theme.darkAlgorithm
              : theme.defaultAlgorithm,
        }}
        locale={locale}
      >
        <App>
          <div className="safe-area-container">
            {children}
          </div>
        </App>
      </ConfigProvider>
    </>
  );
}

const RootProvider = ({ children }: React.PropsWithChildren) => {
  useEffect(() => {
    // Because the language is saved in the backend, a token is required to obtain the api. However, the login page cannot obtain the language through the getUserInfo api, so the language needs to be saved in localstorage.
    const lng = storage.getLanguage();
    if (lng) {
      i18n.changeLanguage(lng);
    }
  }, []);

  return (
    <TooltipProvider>
      <QueryClientProvider client={queryClient}>
        <ThemeProvider defaultTheme="light" storageKey="ragflow-ui-theme">
          <Root>{children}</Root>
        </ThemeProvider>
      </QueryClientProvider>
    </TooltipProvider>
  );
};
export function rootContainer(container: ReactNode) {
  return <RootProvider>{container}</RootProvider>;
}

// 兜底设置 --safe-area-bottom 变量，兼容iPhone刘海屏
(function() {
  function isIphoneWithSafeArea() {
    const ua = window.navigator.userAgent;
    const isIOS = /iphone/gi.test(ua);
    const ratio = window.devicePixelRatio || 1;
    const screenH = window.screen.height * ratio;
    const screenW = window.screen.width * ratio;
    const safeAreaHeights = [812, 844, 896, 926, 852, 932, 780, 1180, 1179, 1792, 2556, 2796];
    return isIOS && (safeAreaHeights.includes(screenH) || safeAreaHeights.includes(screenW));
  }
  function isAndroidWithSafeArea() {
    const ua = window.navigator.userAgent;
    const isAndroid = /android/gi.test(ua);
    const w = window.screen.width;
    const h = window.screen.height;
    const ratio = h / w;
    // 18:9 及以上比例的屏幕通常为全面屏
    return isAndroid && ratio > 1.97;
  }
  if (typeof window !== 'undefined' && typeof document !== 'undefined') {
    if (isIphoneWithSafeArea()) {
      document.body.style.setProperty('--safe-area-bottom', '34px');
    } else if (isAndroidWithSafeArea()) {
      // 安卓全面屏手势区一般24px，部分厂商可适当调大
      document.body.style.setProperty('--safe-area-bottom', '24px');
    } else {
      document.body.style.setProperty('--safe-area-bottom', '0px');
    }
  }
})();
